<!--
 * @Author: your name
 * @Date: 2021-03-26 09:07:49
 * @LastEditTime: 2021-04-08 17:14:23
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \testc:\Users\JOJO\Desktop\vue-demo\my-app\src\components\HelloWorld.vue
-->
<template>
  <div class="login" v-loading="loading">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size:26px">注册</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="login"
          >去登录</el-button
        >
      </div>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="学号" prop="username">
          <el-input
            type="username"
            v-model="ruleForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="PasToggle" label="密码" prop="password">
          <el-input type="text" v-model="ruleForm.password" autocomplete="off">
            <i
              slot="suffix"
              title="隐藏密码"
              @click="changePass"
              style="cursor:pointer;"
              class="el-icon-video-pause"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item v-if="!PasToggle" label="密码" prop="password">
          <el-input
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
          >
            <i
              slot="suffix"
              title="显示密码"
              @click="changePass"
              style="cursor:pointer;"
              class="el-icon-video-play"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
            type="name"
            v-model="ruleForm.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="ruleForm.gender">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学院" prop="classId">
          <el-cascader
            style="width:100%"
            :options="options"
            v-model="ruleForm.classId"
            placeholder="请选择"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="ruleForm.birthday"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
            <!-- timestamp -->
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >注册</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import userApi from "../../api/user";
export default {
  data() {
    var validateUser = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        clearTimeout(this.setTime);
        this.setTime = setTimeout(async () => {
          const { msg } = await userApi.getValidate(value);
          if (msg === "学号不可用") {
            callback(new Error(msg));
          } else {
            callback();
          }
        }, 1000);
      }
    };
    var validatePass = (rule, value, callback) => {
      const re = /^[0-9]+.?[0-9]*$/;
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (!re.test(value - 0)) {
          callback(new Error("密码只能是数字"));
          return;
        }
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入邮箱"));
      } else {
        clearTimeout(this.setTime1);
        this.setTime1 = setTimeout(async () => {
          const { msg } = await userApi.getEmail(value);
          if (msg === "邮箱不可用") {
            callback(new Error(msg));
          } else {
            callback();
          }
        }, 1000);
      }
    };
    //学院
    var validateColleges = (rule, value, callback) => {
      if (value.length == 0) {
        callback(new Error("请选择学院"));
      } else {
        if (value.length == 2) {
          callback(new Error("抱歉,您的班级还未录入,请联系管理员"));
          return;
        }
        callback();
      }
    };
    return {
      //学院下拉
      options: [],
      setTime: null,
      setTime1: null,
      PasToggle: false, //是否显示密码
      loading: false,
      ruleForm: {
        username: "",
        password: "",
        email: "",
        gender: "男",
        classId: "",
        birthday: "",
        name: ""
      },
      rules: {
        username: [
          { required: true, validator: validateUser, trigger: "blur" }
        ],
        password: [
          { required: true, validator: validatePass, trigger: "blur" }
        ],
        // email: [
        //   { required: true, validator: validateEmail, trigger: "blur" },
        //   {
        //     type: "email",
        //     message: "请输入正确的邮箱地址",
        //     trigger: ["blur", "change"]
        //   }
        // ],
        gender: [{ required: true, message: "请选择性别" }],
        classId: [
          { required: true, validator: validateColleges, trigger: "change" }
        ],
        birthday: [{ required: true, message: "请选择生日" }],
        name: [{ required: true, message: "请输入名称" }]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          this.loading = true;
          console.log(this.ruleForm);
          let data = {
            code: this.ruleForm.username,
            password: this.ruleForm.password,
            mail: this.ruleForm.email,
            classId: this.ruleForm.classId[2],
            birth: this.ruleForm.birthday,
            gender: this.ruleForm.gender === "男" ? 0 : 1,
            name: this.ruleForm.name
          };
          let { code } = await userApi.reg(data);
          if (code === 0) {
            this.loading = false;
            this.$message({
              message: "注册成功！！！goodboy",
              type: "success"
            });
            this.$router.push("/login/" + this.ruleForm.username);
          } else {
            this.loading = false;
            this.$message.error("注册失败了！！！");
          }
        } else {
          this.$message.error("请认真填写");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    changePass() {
      this.PasToggle = !this.PasToggle;
    },
    login() {
      this.$router.push("/login");
    }
  },
  async mounted() {
    const data = await userApi.getColleges();
    //遍历出学院树需要的结构
    let options = [];
    for (let index = 0; index < data.length; index++) {
      let obj = {};
      obj.value = data[index].id;
      obj.label = data[index].campus;
      obj.children = [];
      if (options.length === 0) {
        options.push(obj);
      }
      for (let i = 0; i < options.length; i++) {
        if (options[i].label == obj.label) {
          break;
        } else if (i == options.length - 1) {
          options.push(obj);
        }
      }
    }
    data.map(item => {
      options.map(item1 => {
        if (item1.label == item.campus) {
          let obj = [];
          item.children.map(item => {
            obj.push({
              value: item.id,
              label: item.classGrade + "级" + item.classNumber + "班"
            });
          });
          item1.children.push({
            label: item.name,
            value: item.id,
            children: obj.length > 0 ? obj : null
          });
        }
      });
    });
    this.options = options;
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.login {
  background: url("../../assets/one.jpg") no-repeat;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}
.clearfix {
  display: flex;
  justify-content: space-between;
}
/* .clearfix:before,
.clearfix:after {
  display: table;
  content: "";
} */
.clearfix:after {
  clear: both;
}

.box-card {
  width: 400px;
}
</style>
